import { requestWithAuth } from '../utils/request';
import { routerRedux } from 'dva/router';
import { Toast } from 'antd-mobile';

import config from '../config';
export default {
    namespace: 'pay',
    state: {
        form:'',
        formName:'',
        payState:'PAY_NO',
    },
    subscriptions: {

    },
    effects: {
        /**
         * param in payload
         * @param {cart} Array 一系列物品的ID
         * 
         * 向后台创建订单并且将订单号返回和总价格和支付宝前端参数
         * ，路由转移到付款页面显示付款信息
         * 
         */
        *createOrder({payload:{cart}},{put}){
            const params = {
                cart,
            }
            if (cart.length === 0){
                Toast.fail('未选择课程');
                return;
            }
            const res = yield requestWithAuth(config.requestUrl + "/api/v1/order",{
                method:'post',
                body:JSON.stringify(params)
            });
            console.log(res);
            if (!res.data){
                Toast.fail('创建订单失败');
                return;
            } else if (res.data.code === '40001'){
                Toast.fail('购物车中有已购课程');
                return;
            }
            const{data:{form,formName}} = res;
            yield put({type:'createOrderSuccess',payload:{form,formName}})
            yield put(routerRedux.push('/redirect'));
            //
        },
        *getPayResult({payload:{cid,order_id}},{put}){
            console.log('pay');
            // TODO:
            // if (orderid.slice(-5) !== cid){
            // }
            const res = yield requestWithAuth(`${config.requestUrl}/api/v1/order/${order_id}`,{
                mothod:'get',
            })
            const {data:{result}} = res;
            if (!result && result.code !== 0){
                Toast.fail('查询出错');
                return;
            } else {
                if (result.status === 'TRADE_SUCCESS') {
                    yield put({type:'paySuccess'});
                }
            }
        }
    },
    reducers: {
        createOrderSuccess(state, action){
            return {...state, form:action.payload.form, formName:action.payload.formName, payState:'PAY_UNFINISH'};
        },
        paySuccess(state){
            return {...state, payState:'PAY_SUCCESS'}
        }
    }
}